package come.itheima.springbootwebmybatistlias.interceptor;

import com.alibaba.fastjson.JSONObject;
import come.itheima.springbootwebmybatistlias.pojo.Result;
import come.itheima.springbootwebmybatistlias.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    //目标资源方法运行前运行，返回true，放行，反之不放行
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        System.out.println("preHandle....");

        //获取请求url
        String url = req.getRequestURI().toString();
        log.info("请求的url{}", url);


        //判断请求url是否包含Login，若包含则是登陆操作，放行
        if (url.contains("login")) {
            log.info("这是登陆操作");
            return true;
        }

        //获取请求头的令牌
        String jwt = req.getHeader("token");

        //判断令牌是否存在，若不存在，返回错误结果
        if (!StringUtils.hasLength(jwt)) {//判断是否为空字符串
            log.info("请求头为空");
            Result error = Result.error("NOT_LOGIN");
            //手动转换 对象->json ----------->阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;

        }

        //解析令牌，若失败则返回错误结果
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {//jwt解析失败
            e.printStackTrace();
            log.info("解析令牌失败");
            Result error = Result.error("NOT_LOGIN");
            //手动转换 对象->json ----------->阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }

        //放行
        log.info("令牌合法");
        return true;

    }

    //目标资源方法运行后运行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle....");
    }

    //视图渲染完毕后运行，最后运行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
